package com.rural.bus.driver.net;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.rural.bus.driver.R;
import com.rural.bus.driver.utils.ToastUtil;

public class MyHttpUtil {
	
	private HttpUtils mHttp;
	private RequestParams mParams;
	private List<NameValuePair> mPairs=new ArrayList<NameValuePair>();
	
	public MyHttpUtil(){
		mHttp=new HttpUtils();
		mParams=new RequestParams();
	}
	
	public void addBodyParm(String name,String value){
//		params.add
		NameValuePair pair=new BasicNameValuePair(name, value);
		mPairs.add(pair);
	}
	
	public void send(String url,final OnNetCallback callback){
		for(NameValuePair pair:mPairs){
			mParams.addBodyParameter(pair);
		}
		mHttp.send(HttpMethod.POST, url,mParams, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				callback.fail(arg1);
				ToastUtil.showToast(R.string.net_error);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JSONObject object=null;
				try{
					object=new JSONObject(arg0.result);
					callback.success(object);
//					if(object.get("status").equals("0")){
//						callback.success(object.getJSONObject("result"));
//					}else{
//						callback.fail(arg0.result);
//						if(arg0.result != null){
//							ToastUtil.showToast(arg0.result);
//						}
//					}
				}catch(JSONException e){
					Log.e("httputil", e.getMessage());
					callback.success(object);
				}	
			}
		});
	}

}
